package com.huposoft.littleant.handler;

import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.AddDomainRecordRequest;
import com.aliyuncs.alidns.model.v20150109.AddDomainRecordResponse;
import com.aliyuncs.alidns.model.v20150109.DeleteDomainRecordRequest;
import com.aliyuncs.alidns.model.v20150109.DeleteDomainRecordResponse;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordInfoRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordInfoResponse;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordRequest;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.huposoft.littleant.entity.IPRecord;
import com.huposoft.littleant.util.AliyunConst;
import com.huposoft.littleant.util.GetIP;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.UUID;

/***
 * dns 域名 Handler
 * 文档地址：https://help.aliyun.com/document_detail/29776.html?spm=5176.doc29699.6.614.vXIo2V
 * @Auther: anin
 * @Date: 2019/12/19 17:03
 * @version : V1.0
 */
public class AliyunDNSHandler {

    public static String NOW_IP;

    static{
        NOW_IP = GetIP.getNowIP();
    }

    /**
     * 获取dns记录列表
     * @param dns   域名
     * @return
     */
    public static String getDescribeDomainRecords(String dns)  {
        IAcsClient client = getClient();

        DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest();
        request.setRegionId(AliyunConst.REGION_ID);
        request.setDomainName(AliyunConst.IP);

        try {
            DescribeDomainRecordsResponse response = client.getAcsResponse(request);
//            System.out.println(new Gson().toJson(response));
            return new Gson().toJson(response);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return "error";
    }

    /**
     * 添加一条DNS解析记录
     * @param rr    主机记录
     * @param type  类型
     * @param value 记录值
     * @return
     */
    public static String insertDNSRecord(String rr,String type,String value){
        IAcsClient client = getClient();

        AddDomainRecordRequest request = new AddDomainRecordRequest();
        request.setRegionId(AliyunConst.REGION_ID);
        request.setDomainName(AliyunConst.IP);
        request.setRR(rr);
        request.setType(type);
        request.setValue(value);

        try {
            AddDomainRecordResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
            return "success";
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return "error";
    }

    /**
     * 删除一条DNS解析记录
     * @param RecordId  DNS记录id
     * @return
     */
    public static String deleteDNSRecord(String RecordId){
        IAcsClient client = getClient();

        DeleteDomainRecordRequest request = new DeleteDomainRecordRequest();
        request.setRegionId(AliyunConst.REGION_ID);
        request.setRecordId(RecordId);

        try {
            DeleteDomainRecordResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
            return "success";
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return "error";
    }

    /**
     * 修改DNS记录值
     * @return
     */
    public static String updateDNSRecord(String recordId,String rr,String type,String value){
        IAcsClient client = getClient();

        UpdateDomainRecordRequest request = new UpdateDomainRecordRequest();
        request.setRegionId(AliyunConst.REGION_ID);
        request.setRecordId(recordId);
        request.setRR(rr);
        request.setType(type);
        request.setValue(value);

        try {
            UpdateDomainRecordResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
            return "success";
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return  "error";
    }

    /**
     * 根据记录id获取记录
     * @param RecordId 记录id
     * @return
     */
    public static IPRecord getOne(String RecordId){
        IAcsClient client = getClient();

        DescribeDomainRecordInfoRequest request = new DescribeDomainRecordInfoRequest();
        request.setRegionId(AliyunConst.REGION_ID);
        request.setRecordId(RecordId);

        try {
            DescribeDomainRecordInfoResponse response = client.getAcsResponse(request);
            return JSONArray.parseObject(new Gson().toJson(response), IPRecord.class);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return null;
    }

    /**
     * 登录
     * @return
     */
    private static IAcsClient getClient(){
        DefaultProfile profile = DefaultProfile.getProfile(AliyunConst.REGION_ID, AliyunConst.ACCESS_KEY, AliyunConst.ACCESS_KEY_SECRET);
        return new DefaultAcsClient(profile);
    }

    /**
     * 根据解析记录名查询阿里dns的记录值ip是否和当前一致
     * @param RecordName 解析记录名
     * @return 如果需要更改返回更改的recordId
     */
    public static String isSameIpByRecordName(String RecordName){
        String recordId = getRecordIdByRecordName(RecordName);
        if(recordId.equals("404")){
            System.err.println("未找到该条记录！");
            return null;
        }
        IPRecord  record = getOne(recordId);
        System.err.println(RecordName+"."+AliyunConst.IP+" 的DNS解析记录值为 ["+record.getValue()+"]");
        if(record != null && NOW_IP != null && NOW_IP != ""){
            if(record.getValue().equals(NOW_IP)){
                System.err.println(RecordName+"."+AliyunConst.IP+" 的DNS解析记录值与当前一致，无需更改!");
                return "no change";
            }else{
                System.err.println(RecordName+"."+AliyunConst.IP+" 的DNS解析记录值有变化，需要执行更改!");
                return recordId;
            }

        }
        return null;
    }

    /**
     * 根据解析记录名查询解析记录名id
     * @param RecordName 解析记录名
     * @return
     */
    public static String getRecordIdByRecordName(String RecordName){

        String jsonMap = getDescribeDomainRecords(AliyunConst.IP);

        Map map = (Map)JSON.parse(jsonMap);
        String recordListJson = map.get("domainRecords")+"";

        List<IPRecord> personList = JSONArray.parseArray(recordListJson, IPRecord.class);
        for (IPRecord iPRecord:personList) {
            if(iPRecord != null && iPRecord.getRR() != null && iPRecord.getRR().equals(RecordName)){
                return iPRecord.getRecordId();
            }
        }
        return "404";
    }

    public static void main(String[] args) {
        Props props = new Props("test.properties");
        String user = props.getProperty("user");
        System.out.println(user);

    }
}
